from flask import render_template,url_for
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import os
import click


prefix = 'sqlite:///'
app = Flask(__name__)
app.config['DEBUG'] = True
app.config['SQLALCHEMY_DATABASE_URI'] = prefix + os.path.join(app.root_path, 'data.db')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False  # 关闭对模型修改的监控
# 在扩展类实例化前加载配置
db = SQLAlchemy(app)



class User(db.Model):  # 表名将会是 user（自动生成，小写处理）d
    id = db.Column(db.Integer, primary_key=True)  # 主键
    name = db.Column(db.String(20))  # 名字
class Movie(db.Model):  # 表名将会是 movie
    id = db.Column(db.Integer, primary_key=True)  # 主键
    title = db.Column(db.String(60))  # 电影标题
    year = db.Column(db.String(4))  # 电影年份
# @app.context_processor
# def context():
#     user=User.query.first()
#     return dict(user,user)
@app.context_processor
def inject_user():  # 函数名可以随意修改
    user = User.query.first()
    return {'user':user}  # 需要返回字典，等同于 return {'user': user}



@app.cli.command()#注册为命令
@click.option('--drop', is_flag=True, help='Create after drop.')  # 设置选项
def initdb(drop):
    """Initialize the database."""
    if drop:  # 判断是否输入了选项
        db.drop_all()
        click.echo('I删除了.')
    db.create_all()
    click.echo('Initialized database.')  # 输出提示信息

@app.cli.command()
@click.option('--add',is_flag=True,help='‘数据库增加条目’')
def insert(add):
    '''增加数据库条目'''
    user = User(name='Grey Li')  # 创建一个 User 记录
    m1 = Movie(title='Leon', year='1994')  # 创建一个 Movie 记录
    m2 = Movie(title='Mahjong', year='1996')  # 再创建一个 Movie 记录
   # 把新创建的记录添加到数据库会话
    db.session.add(m1)
    db.session.add(m2)
    db.session.commit()  # 提交数据库会话，只需要在最后调用一次即可
username='畅哥'
name = '8888888'
movies = [
    {'title': 'My Neighbor Totoro', 'year': '1988'},
    {'title': 'Dead Poets Society', 'year': '1989'},
    {'title': 'A Perfect World', 'year': '1993'},
    {'title': 'Leon', 'year': '1994'},
    {'title': 'Mahjong', 'year': '1996'},
    {'title': 'Swallowtail Butterfly', 'year': '1996'},
    {'title': 'King of Comedy', 'year': '1999'},
    {'title': 'Devils on the Doorstep', 'year': '1999'},
    {'title': 'WALL-E', 'year': '2008'},
    {'title': 'The Pork of Music', 'year': '2012'},
]

@app.route('/')
def index():
    user1 = User.query.get(3)  # 读取用户记录
    movies = Movie.query.all()  # 读取所有电影记录
    return render_template('index.html', user=user1, movies=movies)
@app.route('/index')
def zuishuaide():
    return render_template('index.html', username=username)
@app.route('/user/<username>')
def user_info(username):
    return f'地址上传入的用户名称: {username} ！~'

@app.route('/test')
def test_url_for():
    print(url_for('hello_world'))  # 输出：/
    print(url_for('user_info', username='mige'))  # 输出：/user/mige
    print(url_for('user_info', username='zatan'))  # 输出：/user/zatan
    print(url_for('test_url_for'))  # 输出：/test
    # 下面这个调用传入了多余的关键字参数，它们会被作为查询字符串附加到 URL 后面。
    print(url_for('test_url_for', num=4 ** 2))  # 输出：/test?num=16
    return '<h1>Test page</h1>'\
           f'<h2>{username}是最帅的人<h2>'

@app.errorhandler(404)  # 传入要处理的错误代码
def page_not_found(e):  # 接受异常对象作为参数
    user = User.query.first()
    return render_template('404.html'),404  # 返回模板和状态码
@app.route('/857')
def zuishuaide():
    return render_template('index.html', username=username)

@app.cli.command()
def forge():fsan
    """Generate fake data."""
    db.create_all()

    # 全局的两个变量移动到这个函数内

    name = 'leeeeee'
    movies = [
        {'title': 'My Neighbor Totoro', 'year': '1988'},
        {'title': 'Dead Poets Society', 'year': '1989'},
        {'title': 'A Perfect World', 'year': '1993'},
        {'title': 'Leon', 'year': '1994'},
        {'title': 'Mahjong', 'year': '1996'},
        {'title': 'Swallowtail Butterfly', 'year': '1996'},
        {'title': 'King of Comedy', 'year': '1999'},
        {'title': 'Devils on the Doorstep', 'year': '1999'},
        {'title': 'WALL-E', 'year': '2008'},
        {'title': 'The Pork of Music', 'year': '2012'},
]
    user = User(name=name)
    db.session.add(user)
    for m in movies:
        movie = Movie(title=m['title'], year=m['year'])
        db.session.add(movie)
    db.session.commit()

    click.echo('Done.')




if __name__ == "__main__":
    app.run()
